import { createRouter, createWebHistory } from 'vue-router';
import Recommend from './pages/Recommend.vue';
import Login from './pages/Login.vue';
import Register from './pages/Register.vue';
import MovieDetail from './pages/MovieDetail.vue';
import MoviePlayer from './pages/MoviePlayer.vue';
import UserRatings from './pages/UserRatings.vue';
import HotMovies from './pages/HotMovies.vue';
import Watchlist from './pages/Watchlist.vue';
import Movies from './pages/Movies.vue';

const routes = [
  { path: '/', redirect: '/recommend' },
  { path: '/recommend', component: Recommend },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/movie/:id', component: MovieDetail, name: 'movie' },
  { path: '/player/:id', component: MoviePlayer, name: 'player', meta: { requiresAuth: true } },
  { path: '/user-ratings', component: UserRatings, meta: { requiresAuth: true } },
  { path: '/watchlist', component: Watchlist, meta: { requiresAuth: true } },
  { path: '/hot', component: HotMovies, name: 'hot' }
  ,{ path: '/movies', component: Movies, name: 'movies' }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局路由守卫：受限页面必须已登录
router.beforeEach((to, _from, next) => {
  const token = (typeof window !== 'undefined') ? localStorage.getItem('token') : null
  const requiresAuth = to.matched.some(r => r.meta && r.meta.requiresAuth)

  // 已登录用户访问登录页，跳回来源或首页
  if (to.path === '/login' && token) {
    const redirect = (to.query && to.query.redirect) ? String(to.query.redirect) : '/recommend'
    next(redirect)
    return
  }

  if (requiresAuth && !token) {
    next({ path: '/login', query: { redirect: to.fullPath } })
    return
  }
  next()
})

export default router;